#include "Billboard.h"
#include "Game.h"

Billboard::Billboard()
{

}

Billboard::Billboard(const Billboard&)
{

}

Billboard Billboard::operator=(Billboard const&)
{
	return Billboard();
}

Billboard::~Billboard()
{

}

bool Billboard::Initialize(int pCount, Texture* pTexture, BasicEffect* pShader)
{
	D3D11_SUBRESOURCE_DATA vertexData;
	HRESULT result;
	D3D11_BUFFER_DESC vertexBufferDesc;

	mShader = pShader;
	mTexture = pTexture;

	mDeviceContext = CDirect3D::Instance()->GetDeviceContext();

	// Set up the description of the static vertex buffer.
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(VertexTypeBillboard) * pCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	VertexTypeBillboard *vertices = new VertexTypeBillboard[pCount];

	// Give the subresource structure a pointer to the vertex data.
    vertexData.pSysMem = vertices;
	vertexData.SysMemPitch = 0;
	vertexData.SysMemSlicePitch = 0;

	// Now create the vertex buffer.
    result = CDirect3D::Instance()->GetDevice()->CreateBuffer(&vertexBufferDesc, &vertexData, &mVertexBuffer);
	if(FAILED(result))
	{
		return false;
	}

	delete vertices;
}

void Billboard::Dispose()
{

}

void Billboard::UpdateBillboard(VertexTypeBillboard* pSpritesData, int pSpritesCount)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	VertexTypeBillboard* verticesPtr;

	mSpritesCount = pSpritesCount;

	// Lock the vertex buffer.
	result = mDeviceContext->Map(mVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

	// Copy the data into the vertex buffer.
	memcpy(mappedResource.pData, pSpritesData, (sizeof(VertexTypeBillboard) * pSpritesCount));

	// Unlock the vertex buffer.
	mDeviceContext->Unmap(mVertexBuffer, 0);
}

void Billboard::Render()
{
	XMFLOAT4X4 worldMatrix;
	XMStoreFloat4x4(&worldMatrix, XMMatrixIdentity());
	XMFLOAT4X4* viewMatrix = Game::Instance()->GetCamera()->GetViewMatrix();
	XMFLOAT4X4* projectionMatrix = CDirect3D::Instance()->GetProjectionMatrix();

	unsigned int stride;
	unsigned int offset;

	stride = sizeof(VertexTypeBillboard); 
	offset = 0;

	mDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
	//mDeviceContext->IASetInputLayout(mShader->GetBillboardInputLayout());
	mDeviceContext->IASetVertexBuffers(0, 1, &mVertexBuffer, &stride, &offset);
	
	mShader->SetTexture(mTexture);
	mShader->SetTransformsMatrices(worldMatrix, *viewMatrix, *projectionMatrix);
	mShader->RenderBillboard(mSpritesCount);
}
